<?php


namespace app\common\model;


use app\common\lib\ZhyxMongo;
use app\Request;
use catcher\Code;
use catcher\exceptions\FailedException;
use think\model\Collection;

class DiseasePatientTask extends BaseModel
{
    public function getTaskTagAttr($value, $data): array
    {
        $arr = ["content" => "宣教文章", "form" => "表单随访", "tel" => "电话随访", "plan" => "复诊计划"];
        $step = $data["step_detail"];
        $taskTag = [];
        foreach ($step as $k => $v) {

            // $taskName = '[' . ($arr[$v["task_type"]] ?? "其他") . ']';

            $taskTag[] = ($k + 1) . "." . $v["task_name"];
            /*if (isset($v["attachments"]) && !empty($v["attachments"])) {
                foreach ($v["attachments"] as $ak => $av) {
                    $taskName .= $av["attachment_title"];
                    $taskTag[] = $taskName;
                }
            } else {
                $taskTag[] = $taskName;
            }*/

        }
        return $taskTag;
    }

    public function getTaskNodeAttr($value, $data): string
    {
        $arr = ["day" => "天", "week" => "周", "month" => "月", "year" => "年"];
        return $data["step_type"]["name"] . ($data["step_is_repeat"] === true ? "每" : "") . $data["step_start_value"] . $arr[$data["step_start_type"]];
    }

    public function getPatientInfoAttr($value, $data)
    {
        return (new PatientInfo())->where("patientId", "=", $data["patient_id"])->field(["inage", "idno"])->find();

    }

    public function getPlanListAttr($value, $data)
    {

        #状态  -1 未开启 0待进行 1进行中 2已完成 3已过期
        $arr = [0 => "待进行", 1 => "进行中", 2 => "已完成", 3 => "已过期"];
        if (isset($value["plan_task_id"])) {
            $value["plan_task_id"] = (string)$value["plan_task_id"];
        }
        if (isset($value["plan_task_status"])) {
            $value["plan_task_status_desc"] = $arr[$value["plan_task_status"]] ?? "未知";
        }
        return $value;
    }


    public function getLists(Request $request, $condition): array
    {

        $modelData = [];
        $userId = $request->user()->id;
        $totalCount = 0;
        $totalPage = 1;
        $page = $request->param("page", 1, "int") ?? 1;
        $limit = $request->param("limit", 20, "int") ?? 1;
        $pipeline = [
            ['$match' => ['doctors.docotr_id' => $userId, 'deleted_at' => 0]],
            ['$sort' => ['_id' => -1]], // 添加排序操作
            ['$unwind' => ['path' => '$planList', 'preserveNullAndEmptyArrays' => true]],
            ['$match' => $condition]
        ];
       
      
        $list = $this->cmd([
            'aggregate' => 'disease_patient_task',
            'pipeline' => $pipeline,
            'explain' => false
        ]);
        
        $totalCount = count($list);
        if ($totalCount > 0) {
            $pipeline[] = ['$skip' => ($page - 1) * $limit];
            $pipeline[] = ['$limit' => $limit];
        }
        $result = $this->cmd([
            'aggregate' => 'disease_patient_task',
            'pipeline' => $pipeline,
            'explain' => false
        ]);

        if (!empty($result)) {
            $modelData = Collection::make($result)->map(function ($item) {
                $item = new DiseasePatientTask($item);
                $item->append(["task_tag", "task_node", "patient_info"])->visible(["patient_name", "patient_sex", "disease_name", "id", "planList"]);
                return $item;
            })->all();
        }
        return ['count' => $totalCount, 'limit' => $limit, "current" => $page, 'data' => $modelData, 'code' => Code::SUCCESS];
    }

    public function getListByPatientId(string $patientId): array
    {
        $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task');
        $cursor = $collection->aggregate([['$match' => ['patient_id' => $patientId, 'deleted_at' => 0]], ['$unwind' => ['path' => '$planList', 'preserveNullAndEmptyArrays' => false]], ['$match' => ['planList.plan_task_status' => ['$eq' => 2]]], ['$project' => ['_id' => false, 'task_id' => '$planList.plan_task_id', 'plan_task_status' => '$planList.plan_task_status', 'plan_date' => '$planList.plan_date', 'complete_date' => '$planList.complete_date', 'task_name' => '$planList.plan_title', 'latest_status_text' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$planList.plan_task_status', 1]], 'then' => '进行中'], ['case' => ['$eq' => ['$planList.plan_task_status', 2]], 'then' => '已完成'], ['case' => ['$eq' => ['$planList.plan_task_status', 3]], 'then' => '已终止']], 'default' => '待开启']], 'path_name' => '$disease_name']]]);
        return iterator_to_array($cursor);
    }


}